package com.lagou.java.sqlSession;

import com.lagou.java.pojo.Configration;
import com.lagou.java.pojo.MapStatement;
import com.lagou.java.utils.GenericTokenParser;
import com.lagou.java.utils.ParameterMapping;
import com.lagou.java.utils.ParameterMappingTokenHandler;
import com.mysql.cj.util.StringUtils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.ParameterizedType;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{

    @Override
    public <E> List<E> query(Configration configration, MapStatement mapStatement, Object... args) throws Exception {
        //注册驱动, 获取连接
        Connection connection = configration.getDataSource().getConnection();
        //获取sql语句
        String sql = mapStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //获取参数的全路径
        String parameterType = mapStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        //设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();

        //参数类型为引用类型
        if (!parameterTypeClass.getPackage().getName().equals("java.lang")) {
            for (int i = 0; i < parameterMappingList.size(); i++) {
                ParameterMapping parameterMapping = parameterMappingList.get(i);
                String content = parameterMapping.getContent();

                //反射
                Field declaredField = parameterTypeClass.getDeclaredField(content);
                //暴力访问
                declaredField.setAccessible(true);
                Object o = declaredField.get(args[0]);

                preparedStatement.setObject(i + 1, o);
            }
        //参数类型为基本类型
        } else {
            preparedStatement.setObject(1, args[0]);
        }

        //执行sql
       if(StringUtils.startsWithIgnoreCaseAndWs(sql, "INSERT")
               || StringUtils.startsWithIgnoreCaseAndWs(sql, "UPDATE")
               || StringUtils.startsWithIgnoreCaseAndWs(sql, "DELETE")) {
           List<Integer> list = new ArrayList<>();
           list.add(preparedStatement.executeUpdate());
           return (List<E>) list;

       } else {
           ResultSet resultSet = preparedStatement.executeQuery();
           String resultType = mapStatement.getResultType();
           Class<?> resultTypeClass = getClassType(resultType);

           List<E> resultList = new ArrayList<>();
           while (resultSet.next()) {
               ResultSetMetaData metaData = resultSet.getMetaData();
               Object o = resultTypeClass.newInstance();
               for (int i = 1; i <= metaData.getColumnCount(); i++) {
                   String columnName = metaData.getColumnName(i);
                   Object value = resultSet.getObject(columnName);
                   //使用反射, 根据数据库表和实体库的对应关系, 完成封装
                   PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                   Method writeMethod = propertyDescriptor.getWriteMethod();
                   writeMethod.invoke(o, value);
               }
               resultList.add((E) o);

           }

           return  resultList;
       }
    }

    @Override
    public <E> List<E> insert(Configration configration, MapStatement mapStatement, Object... args) throws Exception {
        //注册驱动, 获取连接
        Connection connection = configration.getDataSource().getConnection();
        //获取sql语句
        String sql = mapStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //获取参数的全路径
        String parameterType = mapStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        //设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(args[0]);

            preparedStatement.setObject(i + 1, o);
        }

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mapStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        List<E> resultList = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                //使用反射, 根据数据库表和实体库的对应关系, 完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultList.add((E) o);

        }

        return  resultList;
    }

    @Override
    public <E> List<E> update(Configration configration, MapStatement mapStatement, Object... args) throws Exception {
        //注册驱动, 获取连接
        Connection connection = configration.getDataSource().getConnection();
        //获取sql语句
        String sql = mapStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //获取参数的全路径
        String parameterType = mapStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        //设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(args[0]);

            preparedStatement.setObject(i + 1, o);
        }

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mapStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        List<E> resultList = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                //使用反射, 根据数据库表和实体库的对应关系, 完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultList.add((E) o);

        }

        return  resultList;
    }

    @Override
    public <E> List<E> delete(Configration configration, MapStatement mapStatement, Object... args) throws Exception {
        //注册驱动, 获取连接
        Connection connection = configration.getDataSource().getConnection();
        //获取sql语句
        String sql = mapStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        //获取预处理对象
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        //获取参数的全路径
        String parameterType = mapStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        //设置参数
        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();
        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();
            //反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);
            //暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(args[0]);

            preparedStatement.setObject(i + 1, o);
        }

        //执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mapStatement.getResultType();
        Class<?> resultTypeClass = getClassType(resultType);

        List<E> resultList = new ArrayList<>();
        while (resultSet.next()) {
            ResultSetMetaData metaData = resultSet.getMetaData();
            Object o = resultTypeClass.newInstance();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {
                String columnName = metaData.getColumnName(i);
                Object value = resultSet.getObject(columnName);
                //使用反射, 根据数据库表和实体库的对应关系, 完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(o, value);
            }
            resultList.add((E) o);

        }

        return  resultList;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if(parameterType != null) {
            return Class.forName(parameterType);
        }
        return null;
    }

    /**
     * 完成对#{}的解析工作, 1.将#{}使用?代替, 2.解析出#{}里面的值进行存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) throws ClassNotFoundException, IllegalAccessException, InstantiationException {
        //标记处理类: 配置标记解析器来完成对占位符的解析处理工作
        ParameterMappingTokenHandler handler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", handler);
        //解析出来的sql
        String parseSql = genericTokenParser.parse(sql);
        //从#{}解析出来的参数名称
        List<ParameterMapping> parameterMappings = handler.getParameterMappings();

        BoundSql boundSql = new BoundSql();
        boundSql.setSqlText(parseSql);
        boundSql.setParameterMappingList(parameterMappings);

        return boundSql;
    }

}
